package com.mamingchao.basic.rmi;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.CharBuffer;
import java.rmi.server.RMIClientSocketFactory;

/**
 * Created by mamingchao on 2021/1/23.
 */
public class ClientSocketFactory implements RMIClientSocketFactory {
    /**
     * Create a client socket connected to the specified host and port.
     *
     * @param host the host name
     * @param port the port number
     * @return a socket connected to the specified host and port.
     * @throws IOException if an I/O error occurs during socket creation
     * @since 1.2
     */
    @Override
    public Socket createSocket(String host, int port) throws IOException {
        Socket socket = new Socket(host,port);
        InputStream inputStream = socket.getInputStream();


        InputStreamReader reader = new InputStreamReader(inputStream);
        CharBuffer cb = CharBuffer.allocate(1024);
        reader.read(cb);
        char[] charContent = cb.array();
        String strContent = cb.toString();
        System.out.println("CharBuffer - Client endpoint receive message " + strContent);

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("I am mamingchang".getBytes());

        return socket;
    }
}
